/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.app.device.service.impl;

import me.zhengjie.modules.app.device.domain.SettingBindInfo;
import me.zhengjie.modules.app.hotel.repository.HotelInfoRepository;
import me.zhengjie.modules.app.hotel.service.dto.HotelInfoDto;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.app.device.repository.SettingBindInfoRepository;
import me.zhengjie.modules.app.device.service.SettingBindInfoService;
import me.zhengjie.modules.app.device.service.dto.SettingBindInfoDto;
import me.zhengjie.modules.app.device.service.dto.SettingBindInfoQueryCriteria;
import me.zhengjie.modules.app.device.service.mapstruct.SettingBindInfoMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Haojie Li
* @date 2021-03-01
**/
@Service
@RequiredArgsConstructor
public class SettingBindInfoServiceImpl implements SettingBindInfoService {

    private final SettingBindInfoRepository settingBindInfoRepository;
    private final SettingBindInfoMapper settingBindInfoMapper;
    private final HotelInfoRepository hotelInfoRepository;

    @Override
    public Map<String,Object> queryAll(SettingBindInfoQueryCriteria criteria, Pageable pageable){
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
        UserDto userDto = jwtUserDto.getUser();
        List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
        if(hotelLists.size()!=0){
            criteria.setHotelNo(hotelLists.get(0).getHotelNo());
        }
        Page<SettingBindInfo> page = settingBindInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<SettingBindInfoDto> map = page.map(i -> {
            String hotelName = hotelInfoRepository.findByHotelNo(i.getHotelNo()).getHotelName();
            SettingBindInfoDto settingBindInfoDto = settingBindInfoMapper.toDto(i);
            settingBindInfoDto.setHotelName(hotelName);
            return settingBindInfoDto;
        });
        return PageUtil.toPage(map);
    }

    @Override
    public List<SettingBindInfoDto> queryAll(SettingBindInfoQueryCriteria criteria){
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
        UserDto userDto = jwtUserDto.getUser();
        List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
        if(hotelLists.size()!=0){
            criteria.setHotelNo(hotelLists.get(0).getHotelNo());
        }
        return settingBindInfoMapper.toDto(settingBindInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public SettingBindInfoDto findById(String id) {
        SettingBindInfo settingBindInfo = settingBindInfoRepository.findById(id).orElseGet(SettingBindInfo::new);
        ValidationUtil.isNull(settingBindInfo.getId(),"SettingBindInfo","id",id);
        return settingBindInfoMapper.toDto(settingBindInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SettingBindInfoDto create(SettingBindInfo resources) {
        resources.setId(IdUtil.simpleUUID());

        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        resources.setCreateTime(LocalDateTime.now());

        return settingBindInfoMapper.toDto(settingBindInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SettingBindInfo resources) {
    	resources.setUpdateBy(SecurityUtils.getCurrentUsername());
    	resources.setUpdateTime(LocalDateTime.now());

        SettingBindInfo settingBindInfo = settingBindInfoRepository.findById(resources.getId()).orElseGet(SettingBindInfo::new);
        ValidationUtil.isNull( settingBindInfo.getId(),"SettingBindInfo","id",resources.getId());
        settingBindInfo.copy(resources);
        settingBindInfoRepository.save(settingBindInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            settingBindInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SettingBindInfoDto> all, HttpServletResponse response) throws IOException {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list = new ArrayList<>();
        for (SettingBindInfoDto settingBindInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("服务器地址", settingBindInfo.getServerAddress());
            map.put("酒店编号", settingBindInfo.getHotelNo());
            map.put("酒店房间编号", settingBindInfo.getHotelRoomNumber());
            map.put("资源版本号", settingBindInfo.getResourceVersion());
            map.put("本地IP地址", settingBindInfo.getLocalIp());
            map.put("设备类型", settingBindInfo.getDeviceType());
            map.put("存储位置", settingBindInfo.getStoragePlace());
            map.put("绑定的MAC地址", settingBindInfo.getBindMac());
            map.put("激活状态", settingBindInfo.getIsActive());
            map.put("创建时间", settingBindInfo.getCreateTime()  == null ? "" : dtf.format(settingBindInfo.getCreateTime()));
            map.put("更新时间", settingBindInfo.getUpdateTime() == null ? "" : dtf.format(settingBindInfo.getUpdateTime()));
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

	@Override
	public boolean isRecordsExist(String hotelNo, String hotelRoomNumber) {
		// TODO Auto-generated method stub
		SettingBindInfo settingBindInfo = settingBindInfoRepository.findByHotelNoAndHotelRoomNumber(hotelNo, hotelRoomNumber);
		if(settingBindInfo == null) {
			return false;
		}else {
			return true;
		}
	}
}
